//
//  AppDelegate.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/16.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "AppDelegate.h"
#import <CYLTabBarController.h>
#import "YLNavigationController.h"
#import "YLLoginViewController.h"
#import "WHTabbarControllerConfig.h"
#import "YLSwitchRootController.h"

#import "SCSecureHelper.h"
#import "SCLoginVerifyView.h"
#import "LaunchIntroductionView.h"
#import "YLShareSDK.h"
#import "YLGlobeHeader.h"
#import <YYModel.h>
#import "YLPushViewModel.h"
// 引入JPush功能所需头文件
#import <JPUSHService.h>
// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import "YLAccountTool.h"
#import "XHVersion.h"

@interface AppDelegate ()<JPUSHRegisterDelegate>
@property (nonatomic, assign) BOOL showVerify;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) SCLoginVerifyView *verifyView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
   // [UITableView appearance]
    
    if (@available(iOS 11.0, *)){//避免滚动视图顶部出现20的空白以及push或者pop的时候页面有一个上移或者下移的异常动画的问题
       // [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        // 去掉iOS11系统默认开启的self-sizing
        
        [UITableView appearance].estimatedRowHeight = 10;
        [UITableView appearance].estimatedSectionHeaderHeight = 0.1;
        [UITableView appearance].estimatedSectionFooterHeight = 0.1;
    }
    
     [XHVersion checkNewVersion];
    
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    self.window.backgroundColor = [UIColor whiteColor];
    
    [YLSwitchRootController switchRootController];
    
    [self.window makeKeyAndVisible];
    
    NSArray *images = @[@"launch1",@"launch2", @"launch3", @"launch4"];
    if (YLScreenH > 750) {
        images = @[@"launch5",@"launch6", @"launch7", @"launch8"];
    }
    
    LaunchIntroductionView *launch =  [LaunchIntroductionView sharedWithImages:images];
    
    launch.currentColor = YLMainColor;
    launch.nomalColor = [UIColor grayColor];
   
    __weak typeof(self) weakSelf = self;
    BOOL gestureOpen = [SCSecureHelper gestureOpenStatus];
    if (gestureOpen) {
        _showVerify = NO;
        SCLoginVerifyView *verifyView = [[SCLoginVerifyView alloc] initWithFrame:CGRectMake(0.0, 0.0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) ];
        verifyView.dismissBlock = ^{
            weakSelf.showVerify = YES;
        };
        [verifyView showView];
    }
    
    [YLShareSDK initialization];
    
    // 注册APNS
    [self initAPNS];
    // 初始化push
    [self initPush:launchOptions];
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    

    return YES;
}

// 接收到通知事件
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    [YLPushViewModel setNewTagsWithInfo:userInfo];
}


- (void)initAPNS
{
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }
}

- (void)initPush:(NSDictionary *)launchOptions
{
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"adb88fdaec151e2488978752"
                          channel:@"aa"
                 apsForProduction:NO
            advertisingIdentifier:nil];
}



- (void)applicationWillResignActive:(UIApplication *)application {

}




- (void)applicationDidBecomeActive:(UIApplication *)application {
  
}


- (void)applicationWillTerminate:(UIApplication *)application {
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    BOOL gestureOpen = [SCSecureHelper gestureOpenStatus];
    if (gestureOpen) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:3 * 60 target:self selector:@selector(needShouShi) userInfo:nil repeats:NO];
    }
}

- (void)needShouShi
{
    if (_timer) {
        __weak typeof(self) weakSelf = self;
        if (_showVerify == YES) {
            BOOL gestureOpen = [SCSecureHelper gestureOpenStatus];
            if (gestureOpen) {
                _showVerify = NO;
                SCLoginVerifyView *verifyView = [[SCLoginVerifyView alloc] initWithFrame:CGRectMake(0.0, 0.0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) ];
                verifyView.dismissBlock = ^{
                    weakSelf.showVerify = YES;
                };
                [verifyView showView];
            }
        }
    
        [_timer invalidate];
        _timer = nil;
    }
}



- (void)applicationWillEnterForeground:(UIApplication *)application {
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
 
    
}



// 当应用在前台运行中，收到远程通知时，会回调这个方法。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    [JPUSHService handleRemoteNotification:userInfo];
}




#pragma mark - 通知相关
#pragma mark 在前台接受到通知会调用 / 当应用在后台状态时，点击push消息启动应用 (ios10在前台接收到不会调用)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 取得 APNs 标准信息内容
    
    //BOOL isActive;
    if (application.applicationState == UIApplicationStateActive) {
      //  isActive = YES;
    } else {
      //  isActive = NO;
        [self jumpToOther:userInfo];
        
    }
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}



- (void)jumpToOther:(NSDictionary *)userInfo
{
    // 得到通知的内容
    [YLPushViewModel pushWithInfo:userInfo];
}


// 添加处理APNs通知回调方法
#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
// iOS 10 在前台收到通知
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}


// iOS 10 Support
// App通知的点击事件
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    [self jumpToOther:userInfo];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}


// 当客户端注册远程通知时，如果成功，则回调第一个，客户端把deviceToken取出来发给服务端，push消息的时候要用。
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    
    [YLPushViewModel setUpMyPushInfo];

    [JPUSHService registerDeviceToken:deviceToken];
}



@end
